﻿namespace Creek.UI.EFML.Base.JS.ScriptingTypes
{
    using System.IO;
    using System.Net;

    public class XmlHttpRequest
    {
        #region Fields

        public dynamic onreadystatechange;

        private int _readyState;

        private HttpWebRequest _webrequest;

        #endregion

        #region Public Properties

        public string mimetype
        {
            get
            {
                return this._webrequest.MediaType;
            }
            set
            {
                this._webrequest.MediaType = value;
            }
        }

        public int readystate
        {
            get
            {
                return this._readyState;
            }
            set
            {
                if (this.onreadystatechange != null)
                {
                    this.onreadystatechange();
                }
                this._readyState = value;
            }
        }

        public string responsetext { get; set; }

        #endregion

        #region Public Methods and Operators

        public void open(string method, string url)
        {
            this._webrequest = (HttpWebRequest)WebRequest.Create(url);
            this._webrequest.Method = method;
            this.readystate = 0;
        }

        public void send(object data)
        {
            if (data == null)
            {
                var resp = (HttpWebResponse)this._webrequest.GetResponse();
                using (Stream s = resp.GetResponseStream())
                {
                    this.responsetext = new StreamReader(s).ReadToEnd();
                    this.readystate = 1;
                }
            }
            else
            {
                using (Stream s = this._webrequest.GetRequestStream())
                {
                    var sw = new StreamWriter(s);
                    sw.Write(data);
                    sw.Flush();
                    this.readystate = 2;
                }
            }
        }

        #endregion
    }
}